<template>
    <!-- 新增/编辑用户 -->
    <el-drawer
        v-model="userParams.visible"
        :title="dialogTitle"
        @open="handleOpen"
        size="1500"
        :close-on-click-modal="true"
    >
        <!-- {{ formData }} -->
        <div class="drawer-main" v-loading="loading">
            <div class="topFrom">
                <div class="titel">基本信息</div>
                <el-form
                    ref="ruleFormRef"
                    :model="queryParams.entity"
                    label-width="100"
                >
                    <el-row gutter="22">
                        <!-- 姓名 -->
                        <el-col :span="4">
                            <el-form-item label="用户名" prop="userName">
                                <el-input
                                    v-model="queryParams.entity.userName"
                                    maxlength="60"
                                    placeholder="请输入用户名关键字"
                                    clearable
                                    @keyup.enter="handleQuery"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="部门名称" prop="deptId">
                                <el-tree-select
                                    clearable
                                    v-model="queryParams.entity.deptId"
                                    :data="deptOptions"
                                    filterable
                                    :props="{
                                        label: 'deptName',
                                        value: 'deptId',
                                        children: 'children'
                                    }"
                                    @keyup.enter="handleQuery"
                                />
                            </el-form-item>
                        </el-col>
                        <el-row :span="4">
                            <el-form-item>
                                <el-button
                                    type="primary"
                                    icon="Search"
                                    @click="handleQuery"
                                >
                                    搜索
                                </el-button>
                                <el-button
                                    icon="Refresh"
                                    @click="handleResetQuery"
                                >
                                    重置
                                </el-button>
                            </el-form-item>
                        </el-row>
                    </el-row>
                </el-form>
            </div>

            <div class="topFrom">
                <div class="titel">编辑内容</div>
                <div class="leftTable">
                    <div class="title">基础用户列表</div>
                    <el-table
                        v-loading="tableLoading"
                        :data="tableData"
                        highlight-current-row
                        border
                        style="width: 100%; height: 440px; overflow-y: auto"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column type="selection" width="55" />
                        <el-table-column
                            v-for="(item, index) in columnData"
                            :key="index"
                            :prop="item.prop"
                            :label="item.label"
                            :width="item.width || ''"
                            :fixed="item.fixed || false"
                            show-overflow-tooltip
                            :resizable="false"
                            align="center"
                        >
                            <template #default="{ row }">
                                <span>{{ row[item.prop] }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <Pagination
                        v-if="total > 0"
                        v-model:total="total"
                        v-model:page="queryParams.pageNo"
                        v-model:limit="queryParams.pageSize"
                        @pagination="handleQuery"
                    />
                </div>
                <div class="contentTabale">
                    <div class="top">
                        <el-button
                            type="success"
                            icon="Right"
                            @click="zhuanyiright"
                            class="btn"
                        >
                        </el-button>
                    </div>
                    <div class="top">
                        <el-button
                            type="success"
                            icon="Back"
                            @click="zhuanyileft"
                            class="btn"
                        >
                        </el-button>
                    </div>
                </div>
                <div class="rightTable">
                    <div class="title">CRM用户列表</div>
                    <el-table
                        :data="tableDateRight"
                        highlight-current-row
                        border
                        style="width: 100%; height: 440px; overflow-y: auto"
                        @selection-change="rightChange"
                    >
                        <el-table-column type="selection" width="55" />
                        <el-table-column
                            v-for="(item, index) in columnData"
                            :key="index"
                            :prop="item.prop"
                            :label="item.label"
                            :width="item.width || ''"
                            :fixed="item.fixed || false"
                            show-overflow-tooltip
                            :resizable="false"
                            align="center"
                        >
                            <template #default="{ row }">
                                <span>{{ row[item.prop] }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="emit('close')">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { reactive, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { batChInsertSales } from './api'
import Pagination from '@/components/Pagination.vue'

import { getUserList, deletetUser } from '@views/userManage/api/userManage'
import { getDeptTree } from '@views/deptManage/api/deptManage'

const props = defineProps({
    userParams: {
        type: Object,
        default: () => {},
        required: true
    }
})
const queryParams = reactive({
    entity: { deptId: '', userName: '' },
    pageNo: 1,
    pageSize: 10
})
const columnData = ref([
    {
        label: '用户名',
        prop: 'userName',
        fixed: 'left'
    }
])
const treeLoading = ref(false)
const total = ref(0)
const tableData = ref([])
const tableDateRight = ref([])

const selectList = ref([])
const handleSelectionChange = (val) => {
    selectList.value = val
}
const zhuanyiright = () => {
    selectList.value.forEach((selectedItem) => {
        const exists = tableDateRight.value.some(
            (item) => item.userId === selectedItem.userId
        )
        if (!exists) {
            tableDateRight.value.unshift(selectedItem)
        }
    })
    tableData.value = tableData.value.filter(
        (item) => !selectList.value.includes(item)
    )
}

// 反向选择
const rightChange = (val) => {
    selectList.value = val
}
const zhuanyileft = () => {
    selectList.value.forEach((selectedItem) => {
        const exists = tableData.value.some(
            (item) => item.userId === selectedItem.userId
        )
        if (!exists) {
            tableData.value.unshift(selectedItem)
        }
    })
    tableDateRight.value = tableDateRight.value.filter(
        (item) => !selectList.value.includes(item)
    )
}
const handleOpenUserDrawer = () => {}
const tableLoading = ref(false)
const deptOptions = ref([])
// 获取部门树
const deptRootOptions = ref([])

const getDeptData = async () => {
    treeLoading.value = true
    const res = await getDeptTree({})
    treeLoading.value = false
    if (res?.code === 200) {
        deptOptions.value = res.data || []
        deptRootOptions.value = [
            { deptName: '全部', deptId: '', children: deptOptions.value }
        ]
    }
}
const emit = defineEmits(['close'])

const loading = ref(false)
const dialogTitle = '批量新增'

const handleSubmit = () => {
    handleSave()
}

const handleSave = async () => {
    if (tableDateRight.value.length === 0) {
        ElMessage.warning('你未选择CRM用户，不能提交为空！')
        return
    }
    const id = tableDateRight.value.map((item) => item.userId)
    const list = id
    try {
        const res = await batChInsertSales(list)
        if (res.code === 200) {
            tableData.value = []
            selectList.value = []
            tableDateRight.value = []
            ElMessage.success('新增成功')
            loading.value = false
            emit('close', true)
        }
    } catch (error) {
        console.error('Request error:', error)
    }
    loading.value = false
}
// 获取数据
const handleQuery = async () => {
    tableLoading.value = true
    const res = await getUserList(queryParams)
    tableLoading.value = false
    if (res?.code === 200) {
        tableData.value = res.data.records || []
        total.value = res.total || 0
    }
}
// 重置表单
const ruleFormRef = ref(null)
const handleResetQuery = () => {
    ruleFormRef.value.resetFields()
    queryParams.pageNo = 1
    handleQuery()
}
// 初始化弹窗
const handleOpen = () => {
    handleQuery()
    getDeptData()
    nextTick(() => {
        ruleFormRef.value.resetFields()
        // deptOptions.value = props.userParams.deptOptions
        // let row = props.userParams.row
        // // 编辑
        // formData.userName = row.userName
        // formDataJueSe.salesLevel = row.salesLevel
        // formDataJueSe.groupLeader = row.groupLeader
        console.log('初始化')
    })
}
</script>

<style lang="less" scoped>
.titel {
    width: 100%;
    height: 60px;
    padding: 0 10px;
    line-height: 60px;
    color: #0a0a0a;
    font-weight: 600;
    font-size: 14px;
    position: relative;
}
.titel::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 20px;
    width: 5px;
    border-radius: 10px;
    background-color: #1943ff;
}
.titleFrom {
    width: 100%;
}
.tablePadding {
    padding: 0 20px;
}
.leftTable {
    width: 45%;
    height: 550px;
    float: left;
    .title {
        width: 100%;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        font-size: 14px;
        color: #0a0a0a;
        font-weight: 600;
        border: 1px solid #eee;
    }
}
.contentTabale {
    width: 10%;
    height: 480px;
    float: left;
    .top {
        width: 100%;
        height: 150px;
        position: relative;
        .btn {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -30px;
            margin-top: 10px;
        }
    }
}
.rightTable {
    width: 45%;
    height: 480px;
    float: right;
    .title {
        width: 100%;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        font-size: 14px;
        color: #0a0a0a;
        font-weight: 600;
        border: 1px solid #eee;
    }
}
</style>
